package com.longge;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: my-code
 * @description:
 * @author: longge
 * @create: 2021-05-01 04:16
 */
public class GenerateParenthesis {

    List<String> res = new ArrayList<>();

    public List<String> generateParenthesis(int n) {

        int left = n, right = n;
        List<String> path = new ArrayList<>();
        backtrack(left, right, path);
        return res;

    }

    private void backtrack(int left, int right, List<String> path) {

        if (left > right) return;
        if (left < 0 || right < 0) return;
        if (left == 0 && right == 0) {
            res.add(path.stream().collect(Collectors.joining()));
        }

        path.add("(");
        backtrack(left - 1, right, path);
        path.remove(path.size() - 1);

        path.add(")");
        backtrack(left, right - 1, path);
        path.remove(path.size() - 1);


    }


}
